// @Author EthanScriptOn
// @Desc
package log_dispatcher

import (
	"gitee.com/fatzeng/srf_switch_basic_components/dispatcher"
	"gitee.com/fatzeng/srf_switch_basic_components/initialization"
	"gitee.com/fatzeng/srf_switch_basic_components/util"
	"gitee.com/fatzeng/srf_switch_log/log_define"
	"math"
	"reflect"
)

var configInstance = func() *dispatcher.DispatcherConfig {
	config := dispatcher.GenerateDispatcherConfig()
	config.AddComponent(log_define.LogCollector, log_define.LogCollectorForward)
	config.AddComponent(log_define.LogFormatter, log_define.LogFormatterForward)
	config.AddComponent(log_define.LogExporter, log_define.Seat)
	return config
}()

var dataDispatcherInstance = func() *initialization.OnceInitializer {
	initializerInstance := initialization.GenerateOnceInitializer(log_define.SwitchLogPositionTag, log_define.LogModuleResourceIdentityInitTag)
	if err := initializerInstance.Set(math.MaxInt, func() (result interface{}, err error) {
		dataDispatcher, err := dispatcher.GenerateDataDispatcher(configInstance, false)
		if err != nil {
			panic(err)
		}
		dataDispatcher.Register(log_define.LogCollectorForward, GenerateLoggerCollectForward())
		dataDispatcher.Register(log_define.LogFormatterForward, GenerateLoggerFormatForward())
		if err := dataDispatcher.Start(); err != nil {
			panic(err)
		}
		return dataDispatcher, nil
	}); err != nil {
		panic(err)
	}
	return initializerInstance
}()

func GetDataDispatcherInstance() (*dispatcher.DataDispatcher, error) {
	dataDispatcherVar, err := dataDispatcherInstance.Get()
	if err != nil {
		return nil, err
	}
	if dataDispatcherConversionInstance, err := util.Assert(dataDispatcherVar, reflect.TypeOf(&dispatcher.DataDispatcher{})); err != nil {
		return nil, err
	} else {
		return dataDispatcherConversionInstance.(*dispatcher.DataDispatcher), nil
	}
}
